package com.zongxingh.falcon.mq.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Introduction:  <简介>
 * Package Name:  com.zongxingh.falcon.mq.utils
 * Project Name:  mq
 * Author:  zongxingh
 * Email： zongxingh@163.com
 * Tel: 157*****778
 * Create Time:  2020/9/22 19:15
 */
public class ExceptionTools {
    private ExceptionTools() {
    }

    /**
     * 将已检查异常转换成未检查异常
     *
     * @param exp
     * @return
     */
    public static RuntimeException cvtUnchecked(Exception exp) {
        if (exp instanceof RuntimeException) {
            return (RuntimeException) exp;
        } else {
            return new RuntimeException(exp);
        }
    }

    /**
     * 将异常错误信息转换成字符串
     *
     * @param exp
     * @return
     */
    public static String getStackTraceAsString(Exception exp) {
        StringWriter strWriter = new StringWriter();
        exp.printStackTrace(new PrintWriter(strWriter));
        return strWriter.toString();
    }

    /**
     * 判断异常是否由某些底层的异常引起.
     *
     * @param ex
     * @param causeExceptionClasses
     * @return
     */
    public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
        Throwable cause = ex.getCause();
        while (cause != null) {
            for (Class<? extends Exception> causeClass : causeExceptionClasses) {
                if (causeClass.isInstance(cause)) {
                    return true;
                }
            }
            cause = cause.getCause();
        }
        return false;
    }
}
